﻿$(function() {
//Declare variable
	var  UserName= $( "#UserName" ),
		Password = $( "#Password" ),
		FirstName = $( "#FirstName" ),
		LastName = $( "#LastName" ),
		Position = $( "#PositionID" ),
		Group = 	$( "#GroupID" ),
		//Branch = 	$( "#BranchID" ),	
		Email = 	$( "#Email" ),
		Telephone = 	$( "#Telephone" ),	
		allFields = $( [] ).add( UserName )
							.add(Password)
							.add(FirstName)
							.add(LastName)
							.add(Email)
							.add(Telephone),
		tips = $( ".validateTips" ),
		button_name="",
		url="a_user.php", 
		ID="",
		AddTitle="Create new User",	
		EditTitle="Update User",	
		rowSelect="";
		
		//Hide Column
		$(".tr_sms").hide();
		
		showLoader();
		 
		Telephone.keypress(function(e){
			//alert(e);
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
				return false;
			}
		});
			
		//get json group
//		$.get(url,{"c":"b"},function(data){
//			var obj=eval('('+data+')');	
//			if (obj != null){
//				 $.each(obj, function(index, text) {
//					$("#cboBranch ,#BranchID").append(
//							$('<option></option>').val(text).html(index)
//						 );
//				});
//			}
//		});
	
 		$.get(url,{"c":"g"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
				$("#cboGroup ,#GroupID").append(
						$('<option></option>').val(index).html(text)
					 );
				});
			}
		});
		
 		$.get(url,{"c":"p"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
				$("#cboPosition ,#PositionID").append(
						$('<option></option>').val(index).html(text)
					 );
				});
			}
		});
 
		$("#cboPosition").append($('<option></option>').val(0).html('All'));
		$("#cboGroup").append($('<option></option>').val(0).html('All'));
		//$("#cboBranch").append($('<option></option>').val(0).html('All'));
		
		//Load First page
		LoadData(1,true);	
		
//		$("#BranchID").live('change',function(){
//			var bid= $("#BranchID option:selected").val();
//		
//			checkBranch_Is_HO(bid);
//		});
		
		function checkBranch_Is_HO(bid){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {'m':'check_ho','bid':bid},
				success: function(data){
					//alert(data);
					var obj=eval('('+data+')');
				  	if (obj['Type']=="1"){
						$(".tr_sms").show();
					}else{
						$(".tr_sms").hide();
					}
				}
			});
		}
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='9' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};	
		
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );

		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
					
		 

		function getData(id){
			var dataSet={'id':id,'m':'detail'};  
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					var obj=eval('('+data+')');
					//check branch
					//checkBranch_Is_HO(obj['BranchID']);
					
				  	for (value in obj){
						txt="#"+value;
						//alert(txt);
						$(txt).val(obj[value]);
						 
						if (value =='Status'){
	 						$("#IsActived").attr('checked',obj[value]=='Actived'? true:false);
						}else if (value=='SMS'){
							$("#SMS").attr('checked',obj[value]=='1'? true:false);
						}
					}
				}
			});
		}
		
		function callAjax(obj,id){
			var m=$("#mode").val();
			var rows=$("#rowCount").attr('innerHTML');
			if (m=="edit"){
				rows=rowSelect.find("td").eq(0).html();
			}
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id,"rows":rows},
				success: function(data){
					if (m=='add'){
						if (data=='error'){
							AddErrorMessage(UserName,UserName.val() + ' already exists' );
						}else{
							//alert(data);
							//Insert data to first row.
							$( "#resultData tbody:first" ).prepend( data ); 
							//Set font color
							$( "#resultData tbody tr:first" ).css('color','blue');
							
							//Plus row number ;
							var rows=$("#rowCount").attr('innerHTML');
							$("#rowCount").attr('innerHTML',parseInt(rows,10)+1);
							
							$( "#dialog-form" ).dialog( "close" );
						}
						
					}else if (m=='edit'){
						rowSelect.html(data);
					}
					// else if (m=='del'){
					// alert(data);
					// }
				
				}
			});
		}
		
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 600,
			zIndex:9999,
			width: 450,
			modal: true,
			open: function() { 
				tips.text( "* fields are required." );
				
				//$("#BranchID option:eq(0)").attr('selected', 'selected');
				$("#GroupID option:eq(0)").attr('selected', 'selected');
				$("#PositionID option:eq(0)").attr('selected', 'selected');
				
				if ($("#mode").val()=="add"){
					//Select brand is HO or not
					//alert($("#BranchID").val());
					//checkBranch_Is_HO($("#BranchID").val());
					
				}else if ($("#mode" ).val() =="edit" || $("#mode" ).val()=="view"){
					//getData(ID);
				}else{
					allFields.val( "" );
				}
			},
			close: function() {
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function getValue(){
			var o = {};
			//get name and value control 
			$( "#dialog-form" ).find('input').each(function(){
				
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					if($(this).attr('type')!="checkbox"){ 
						o[$(this).attr('id')].push($(this).val() || '');
					}
				} else {
					if($(this).attr('type')!="checkbox"){ 
						o[$(this).attr('id')] = $(this).val() || '';
					}
				}
			});
			o["IsActived"] = $("#IsActived").attr('checked')==true?1:0 || '';
			o["SMS"] = $("#SMS").attr('checked')==true?'1':'0'||'0';
			
			$( "#dialog-form" ).find('select').each(function(){
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					o[$(this).attr('id')].push($(this).val() || '');
				}else{
					o[$(this).attr('id')] = $(this).val() || '';
				}
				
			});

			return o;
		}
		function AddErrorMessage(o,n){
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( UserName, "Username",1);
			bValid = bValid && checkInputFile( Password, "Password",1);
			bValid = bValid && checkInputFile( FirstName, "First Name",1);
			bValid = bValid && checkInputFile( Email, "Email",1);
			bValid = bValid && checkRegexp( Email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. admin@oriental.com" );					
			bValid = bValid && checkInputFile( Telephone, "Telephone",1);
			return bValid;
		}
		
		//Add Button
		$( "#btnAdd" ).live('click',function() {
				//set mode
				$("#mode").val("add");
				//set title
				$("#dialog-form").dialog({'title':AddTitle});
				$( "#dialog-form" ).dialog( "open" );
				$( "#dialog-form" ).dialog( "option","buttons",{
					"Create":function(){
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl() ) {
							callAjax(getValue(),0); // call ajax function for add new data
							//$( this ).dialog( "close" );
						}
					},
					"Cancel":function(){$( this ).dialog( "close" );}
				});
			});
			
		$(".btnEdit").live('click',function() {
				$("#mode").val("edit"),
				rowSelect=$(this).parent().parent(),
				ID=$(this).parent().parent().find("td").eq(1).html(),
				getData(ID),
				$("#dialog-form").dialog({'title':EditTitle});
				$("#dialog-form").dialog("open");
				$("#dialog-form").dialog( "option","buttons",{
					"Update":function(){
						var bValid = true;
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl() ) {
							callAjax(getValue(),ID); // call ajax for update 
							$( this ).dialog( "close" );
						}
					}
					,"Cancel":function(){
						$( this ).dialog( "close" );
					}
				}
				);
			});
		$(".btnDel").live('click',function(){
				var tableRow  = $(this).parent().parent().parent();
				var irow=$(this).parent().parent().find("td").eq(0).html();
				
				rowSelect = $(this).parent().parent();
				ID=$(this).parent().parent().find("td").eq(1).html();
				//alert(ID);
				$("#mode").val("del");
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						callAjax({"id":ID},0); 	//Call Ajax delete data
						rowSelect.remove(); // remove row
				
						tableRow.find("tr").each(function(){
							if (irow < parseInt($(this).find("td").eq(0).html()))
								$(this).find("td").eq(0).html( parseInt($(this).find("td").eq(0).html()) - 1 );	
						});
		
						//Remove number
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						
						$( this ).dialog( "close" );
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
			});
		$(".btnView").live('click', function(){
			$("#mode").val("view");
			ID=$(this).parent().parent().find("td").eq(0).html();
			getData(ID); // get detail data 
			allFields.val( "" ).removeClass( "ui-state-error" ),
			$( ".validateTips" ).html(''),
			$("#dialog-form").dialog({'title':ViewTitle}),
			$("#dialog-form").dialog("open"),
			$("#dialog-form").dialog("option","buttons",{
				"Close":function(){
					allFields.attr("readonly","");
					$( this ).dialog( "close" );
					}
				});
		});
		
		$("#btnSearch").click(function(){
			LoadData(1,true);
		});
		
		function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			var dataSet={'m':'search'
						,'name':$("#txtUserName_s").val()	
						,'group':$("#cboGroup").val()
						,'branch':0//$("#cboBranch").val()
						,'position':$("#cboPosition").val()
						,'sms':$("#IsSMS").attr('checked')==true?'1':'0'
						,'page':page
						};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
				//alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				 
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}				
					// var p="<ul>";
					// for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						// p = p +'<li id="'+i+'">'+i+'</li>';
					// }
					// p = p+"</ul>";
					// $("#paging_button ul").remove();
					// $("#paging_button").append(p);
					 
				}
				//$("#"+page).css({'background-color' : '#006699'});
			 });
		}
 
			
	// $("#paging_button li").live('click',function(){
		// $("#paging_button li").css({'background-color' : ''});
 		// LoadData(this.id,false);

	// });		
	
	function setPaging(iTotal){
					 $("#paging_btn").paginate({
					count 		: iTotal,
					start 		: 1,
					display     : 10,
					border					: false,
					text_color  			: '#888',
					background_color    	: '#EEE',	
					text_hover_color  		: 'blue',
					background_hover_color	: '#CFCFCF',
					mouse					: 'press',
					onChange     			: function(page){
												LoadData(page,false);
											  }
				});
		}
		
});
	